package com.example.test.conview.view.tool;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.datamatrix.DataMatrixWriter;
import com.google.zxing.pdf417.PDF417Writer;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.puty.conputyutils.LeoUtils;
import com.puty.conputyview.R;

import java.util.Hashtable;

public class DimensionCodeUtils {
    /**
     * 生成一维码 Bitmap
     * @param content 内容
     * @param width 宽
     * @param height 高
     * @param type 类型
     * @param mergin 循环次数
     * @return Bitmap对象
     */
    public static Bitmap createOneCodeImage(String content, int width,
            int height, BarcodeFormat type, int mergin) {
        if (width < 200) {
            width = 200;
        }

        if (height < 50) {
            height = 50;
        }
        try {
            /**
             * // 文字编码
             * */
            Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");

            BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
                    type, width, height, hints);
            bitMatrix = updateBit(bitMatrix, mergin, 1);
            return toBufferedImage(bitMatrix);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static Bitmap toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        Bitmap image = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        int[] pixel = new int[width * height];
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                pixel[y * width + x] = matrix.get(x, y) ? 0xff000000 : 0x00ffffff;
            }
        }
        image.setPixels(pixel, 0, width, 0, 0, width, height);
        return image;
    }

    /**
     * 去白边
     *
     * @param matrix matrix对象
     * @param margin 循环次数
     * @return
     */
    /**
     * 去白边
     *
     * @param matrix matrix对象
     * @param margin 循环次数
     * @param width 增加宽度
     * @return
     */
    private static BitMatrix updateBit(BitMatrix matrix, int margin, int width) {
        int tempM = margin * 2;
        /**
         * //获取二维码图案的属性
         * */
        int[] rec = matrix.getEnclosingRectangle();
        int resWidth = rec[2] + tempM + width;//去白边有问题，39码会将最右边一条线去掉，(36X0000885395),故宽度在基础上增加一个
        int resHeight = rec[3] + tempM;
        /**
         * // 按照自定义边框生成新的BitMatrix
         * */
        BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
        resMatrix.clear();
        for (int i = margin; i < resWidth - margin; i ++) {
            /**
             * //循环，将二维码图案绘制到新的bitMatrix中
             * */
            for (int j = margin; j < resHeight - margin; j++) {
                if (matrix.get(i - margin + rec[0], j - margin + rec[1])) {
                    resMatrix.set(i, j);
                }
            }
        }
        return resMatrix;
    }

    public static Bitmap qrcreateCodeImage(String content, int width, int height,
                                       BarcodeFormat type, String encoding, int blankSpaceWidth, ErrorCorrectionLevel elevel, boolean isShowLogo, int mergin) {
        Bitmap bitmap = null;
        /**
         * //判断条码类型
         * */
        if (!(type == BarcodeFormat.QR_CODE
                || type == BarcodeFormat.DATA_MATRIX || type == BarcodeFormat.PDF_417))
            return null;
        try {
            /**
             * //判断URL合法性
             * */
            if (content == null || "".equals(content) || content.length() < 1) {
                return null;
            }
            Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
            /**
             * // 设置QR二维码的纠错级别（H为最高级别）具体级别信息
             * */
            hints.put(EncodeHintType.ERROR_CORRECTION, elevel);
            /**
             * //编码
             * */
            hints.put(EncodeHintType.CHARACTER_SET, encoding);
            hints.put(EncodeHintType.MARGIN, blankSpaceWidth);
            /**
             * //图像数据转换，使用了矩阵转换
             * */
            BitMatrix bitMatrix = null;
            if (type == BarcodeFormat.QR_CODE) {
                bitMatrix = new QRCodeWriter().encode(content,
                        type, width, height, hints);
            } else if (type == BarcodeFormat.DATA_MATRIX) {
                bitMatrix = new DataMatrixWriter().encode(content, type, blankSpaceWidth, height, hints);
            } else {
                bitMatrix = new PDF417Writer().encode(content, type, blankSpaceWidth, height, hints);
            }
            /**
             * //去掉白边
             * */
            bitMatrix = updateBit(bitMatrix, mergin, 0);//!!!
            width = bitMatrix.getWidth();
            height = bitMatrix.getHeight();
            int[] pixels = new int[width * height];
            /***
             *
             * //下面这里按照二维码的算法，逐个生成二维码的图片，
             //两个for循环是图片横列扫描的结果
             * */
            for (int y = 0; y < height; y++) {
                for (int x = 0; x < width; x++) {
                    if (bitMatrix.get(x, y)) {
                        pixels[y * width + x] = 0xff000000;
                    } else {
                        pixels[y * width + x] = 0x00ffffff;
                    }
                }
            }
            /***
             * //生成二维码图片的格式，使用ARGB_8888
             * */
            bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
        } catch (WriterException e) {
            e.printStackTrace();
            return null;
        }

        if (isShowLogo) {
            return addLogo(bitmap, BitmapFactory.decodeResource(LeoUtils.getApplication().getResources(), R.mipmap.ic_power_grid));
        } else {
            return bitmap;
        }
    }

    /**
     * 在二维码中间添加Logo图案
     */
    private static Bitmap addLogo(Bitmap src, Bitmap logo) {
        if (src == null) {
            return null;
        }
        if (logo == null) {
            return src;
        }
        //获取图片的宽高
        int srcWidth = src.getWidth();
        int srcHeight = src.getHeight();
        int logoWidth = logo.getWidth();
        int logoHeight = logo.getHeight();

        if (srcWidth == 0 || srcHeight == 0) {
            return null;
        }

        if (logoWidth == 0 || logoHeight == 0) {
            return src;
        }
        //logo大小为二维码整体大小的1/5
        float scaleFactor = srcWidth * 1.0f / 5 / logoWidth;
        Bitmap bitmap = Bitmap.createBitmap(srcWidth, srcHeight, Bitmap.Config.ARGB_8888);
        try {
            Canvas canvas = new Canvas(bitmap);
            canvas.drawBitmap(src, 0, 0, null);
            canvas.scale(scaleFactor, scaleFactor, srcWidth / 2, srcHeight / 2);
            canvas.drawBitmap(logo, (srcWidth - logoWidth) / 2, (srcHeight - logoHeight) / 2, null);
            canvas.save();
            canvas.restore();

        } catch (Exception e) {
            bitmap = null;
            e.getStackTrace();
        }

        return bitmap;
    }

}
